<template>
  <div class="passenger">
    <a-card title="余票信息">
      <a-form layout="inline" :model="formObj">
        <a-form-item>
          <a-date-picker
            v-model:value="formObj.date"
            :disabled-date="disabledDate"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
          />
        </a-form-item>
        <a-form-item>
          <StationSelect v-model:name="formObj.start" width="200px" placeholder="请选择出发站" />
        </a-form-item>
        <a-form-item>
          <StationSelect v-model:name="formObj.end" width="200px" placeholder="请选择到达站" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="getList">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="reset">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>
    <a-table :data-source="dataList" :columns="columns" :pagination="false">
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'operation'">
          <a-space>
            <a-button type="primary" :disabled="isExpire(record)" @click="preset(record)">
              {{ isExpire(record) ? '过期' : '预订' }}
            </a-button>
            <router-link
              :to="{
                path: '/seat',
                query: {
                  date: record.date,
                  trainCode: record.trainCode,
                  start: record.start,
                  startIndex: record.startIndex,
                  end: record.end,
                  endIndex: record.endIndex,
                },
              }"
            >
              <a-button type="primary">座位销售图</a-button>
            </router-link>
            <a-button type="primary" @click="getTrainStation(record)">途经车站</a-button>
          </a-space>
        </template>
        <temaplate v-else-if="column.dataIndex === 'station'">
          {{ record.start }}
          <br />
          {{ record.end }}
        </temaplate>
        <temaplate v-else-if="column.dataIndex === 'time'">
          {{ record.startTime }}
          <br />
          {{ record.endTime }}
        </temaplate>
        <temaplate v-else-if="column.dataIndex === 'duration'">
          {{ calDaration(record.startTime, record.endTime) }}
          <br />
          <div v-if="record.startTime.replaceAll(':', '') > record.endTime.replaceAll(':', '')">
            次日到达
          </div>
          <div v-else>当日到达</div>
        </temaplate>
        <template v-else-if="column.dataIndex === 'ydz'">
          <div v-if="record.ydz >= 0">
            {{ record.ydz }}
            <br />
            {{ record.ydzPrice }}￥
          </div>
          <div v-else>--</div>
        </template>
        <template v-else-if="column.dataIndex === 'edz'">
          <div v-if="record.edz >= 0">
            {{ record.edz }}
            <br />
            {{ record.edzPrice }}￥
          </div>
          <div v-else>--</div>
        </template>
        <template v-else-if="column.dataIndex === 'rw'">
          <div v-if="record.rw >= 0">
            {{ record.rw }}
            <br />
            {{ record.rwPrice }}￥
          </div>
          <div v-else>--</div>
        </template>
        <template v-else-if="column.dataIndex === 'yw'">
          <div v-if="record.yw >= 0">
            {{ record.yw }}
            <br />
            {{ record.ywPrice }}￥
          </div>
          <div v-else>--</div>
        </template>
      </template>
    </a-table>
    <a-pagination
      v-model:current="formObj.page"
      v-model:page-size="formObj.pageSize"
      align="right"
      :total="formObj.total"
      show-size-changer
      style="margin-top: 20px"
      @change="onChange"
    />
    <a-modal v-model:visible="visible" title="途径车站" width="700px" :footer="null">
      <a-table :data-source="trainStationList" :columns="trainStationColumns" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'outTime'">
            {{ record.index == trainStationList.length - 1 ? '-' : record.outTime }}
          </template>
          <template v-if="column.dataIndex === 'stopTime'">
            {{ record.index == trainStationList.length - 1 ? '-' : record.stopTime }}
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { TicketApi } from '@/api/ticket';
import StationSelect from '@/components/Station-Select.vue';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { TrainInfoApi } from '@/api/trainInfo';

onMounted(() => {
  const ticketSearch = JSON.parse(sessionStorage.getItem('ticketSearch') || 'null');
  if (ticketSearch) {
    formObj.value.start = ticketSearch.start;
    formObj.value.end = ticketSearch.end;
    formObj.value.date = ticketSearch.date;
    getList();
  }
});

const router = useRouter();

const columns = ref([
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    width: 80,
  },
  {
    title: '车次编号',
    dataIndex: 'trainCode',
    key: 'trainCode',
    width: 110,
  },
  {
    title: '车站',
    dataIndex: 'station',
    key: 'station',
  },
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
  },
  {
    title: '历时',
    dataIndex: 'duration',
    key: 'duration',
  },
  {
    title: '出发站序',
    dataIndex: 'startIndex',
    key: 'startIndex',
  },
  {
    title: '到站站序',
    dataIndex: 'endIndex',
    key: 'endIndex',
  },
  {
    title: '一等座',
    dataIndex: 'ydz',
    key: 'ydz',
  },
  {
    title: '二等座',
    dataIndex: 'edz',
    key: 'edz',
  },
  {
    title: '软卧',
    dataIndex: 'rw',
    key: 'rw',
  },
  {
    title: '硬卧',
    dataIndex: 'yw',
    key: 'yw',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 150,
    fixed: 'right',
  },
]);

const formObj = ref({
  date: null,
  start: '',
  end: '',
  // date: '2025-10-07',
  // start: '北京西站',
  // end: '郑州东站',
  page: 1,
  pageSize: 10,
  total: 0,
} as {
  date: string | null;
  start: string;
  end: string;
  page: number;
  pageSize: number;
  total: number;
});

const dataList = ref([]);

const getList = async (): Promise<void> => {
  if (!formObj.value.date) {
    message.error('请选择日期');
    return;
  }
  if (!formObj.value.start) {
    message.error('请选择出发站');
    return;
  }
  if (!formObj.value.end) {
    message.error('请选择到达站');
    return;
  }
  const { data } = await TicketApi.query(formObj.value);
  dataList.value = data.records || [];
  formObj.value.total = data.total;
};

const reset = (): void => {
  formObj.value.start = '';
  formObj.value.end = '';
  formObj.value.date = null;
  getList();
};

const onChange = (current: number, pageSize: number): void => {
  console.log(current, pageSize);
  formObj.value.page = current;
  formObj.value.pageSize = pageSize;
  getList();
};
// 不能选择今天以前及两周以后的日期
const disabledDate = (current: any): any => {
  return current && (current <= dayjs().add(-1, 'day') || current > dayjs().add(14, 'day'));
};
// 判断是否超过了火车的发车时间
// 算法其实就是搜索的日期的零点+当前车次发车时间 减去 当前时间，如果小于0则说明已经过了发车时间
const isExpire = (record: any): any => {
  // 标准时间：2000/01/01 00:00:00
  let startDateTimeString = record.date.replace(/-/g, '/') + ' ' + record.startTime;
  let startDateTime = new Date(startDateTimeString);

  //当前时间
  let now = new Date();

  console.log(startDateTime);
  return now.valueOf() >= startDateTime.valueOf();
};

const calDaration = (startTime: string, endTime: string): any => {
  let diff = dayjs(endTime, 'HH:mm:ss').diff(dayjs(startTime, 'HH:mm:ss'), 'seconds');
  return dayjs('00:00:00', 'HH:mm:ss').second(diff).format('HH:mm:ss');
};

const preset = (record: any): void => {
  sessionStorage.setItem('ticketSearch', JSON.stringify(formObj.value));
  router.push({
    path: '/order',
    query: {
      // 传参：加密+stringfy转化
      ticket: encodeURIComponent(JSON.stringify(record)),
    },
  });
  console.log(record);
};
// 途径车站
const visible = ref(false);
const trainStationList = ref([]);
const trainStationColumns = ref([
  {
    title: '站序',
    dataIndex: 'index',
    key: 'index',
    width: 80,
  },
  {
    title: '站名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '进站时间',
    dataIndex: 'inTime',
    key: 'inTime',
  },
  {
    title: '出站时间',
    dataIndex: 'outTime',
    key: 'outTime',
  },
  {
    title: '停战时长',
    dataIndex: 'stopTime',
    key: 'stopTime',
  },
]);
const getTrainStation = async (record: any): Promise<void> => {
  const { data } = await TrainInfoApi.getTrainStation(record.trainCode, record.date);
  trainStationList.value = data || [];
  visible.value = true;
};
</script>

<style scoped lang="less">
.passenger {
  :global(.ant-modal .ant-modal-footer) {
    text-align: center;
  }
}
</style>
